//创建用户项目的仓库信息
import { defineStore } from 'pinia'
import { clearCookie } from '@/utils/cookie'
//引入接口
import { login, getUserInfo, getPermission, getRouters, logout } from '@/api/user'
//引入类型
import { LoginDto } from '@/api/user/type'
//引入我们的常量路由
import { constantRoutes } from '@/router/routes'
import { RouteRecordRaw } from 'vue-router'
// 假设这是你的用户信息类型定义
interface UserState {
  userId: string
  avatar: string
  username: string
  nickName: string
  email: string
  phoneNumber: string
  sex: number
  password: string
  roles: string[]
  permissions: string[]
  routes: RouteRecordRaw[]
}

const useUserStore = defineStore('user', {
  //小仓库
  state(): UserState {
    return {
      userId: '',
      avatar: '',
      username: '',
      nickName: '',
      email: '',
      phoneNumber: '',
      sex: 0,
      password: '',
      roles: [],
      permissions: [],
      routes: constantRoutes //仓库初始化的时候，默认加载我们的常量路由
    }
  },
  //异步处理逻辑的地方
  actions: {
    /**
     * 处理用户登录的方法,不需要我们保存任何数据，因为后端会自动设置到session中，我们只需要调用接口
     * @param loginForm
     */
    async login(loginForm: LoginDto) {
      await login(loginForm)
    },
    /**
     * 获取用户信息
     */
    async getUserInfo() {
      const userInfo = await getUserInfo()
      this.userId = userInfo.userId
      this.avatar = userInfo.avatar
      this.username = userInfo.username
      this.password = userInfo.password
      this.nickName = userInfo.nickName
      this.email = userInfo.email
      this.phoneNumber = userInfo.phoneNumber
      this.sex = userInfo.sex
      //return userInfo
    },
    /**
     * 获取用户(角色和按钮权限)
     */
    async getPermission() {
      const permission = await getPermission()
      this.permissions = permission.permissions
      this.roles = permission.roles
    },
    /**
     * 获取路由信息
     */
    async getRouters() {
      this.routes = await getRouters()
    },
    /**
     * 退出登录
     */
    async logout() {
      await logout()
      this.clearInfo()
    },
    //清空本地信息和cookies信息
    clearInfo() {
      this.userId = ''
      this.avatar = ''
      this.username = ''
      this.password = ''
      this.nickName = ''
      this.email = ''
      this.phoneNumber = ''
      this.sex = 0
      this.permissions = []
      this.roles = []
      this.routes = []
      //清空全部路由，在重新将静态路由添加进去
      this.routes = constantRoutes
      //清空cookies信息
      const cookiesToClear = ['X-Token'] /* 添加其他需要清除的cookie名称 */
      cookiesToClear.forEach((cookieName) => clearCookie(cookieName))
    }
  },
  //计算属性
  getters: {}
})

//对外暴露
export default useUserStore
